package dao;

import java.util.ArrayList;
import java.util.List;

import domain.Balance;

public class BalanceDAO extends GenericDAO<Balance> {

	private static BalanceDAO instance;
	
	public static BalanceDAO getInstance() {
		if (instance == null) {
			instance = new BalanceDAO();
		}
		return instance;
	}

	@Override
	public Balance store(Balance entity) {
		if (entity.getId() != null) {
			return update(entity);
		}
		entity.setId(BalanceDAO.sequenceId++);
		entity.setVersion(0);
		this.entities.put(entity.getId(), entity.clone());
		return entity;
	}

	@Override
	public Balance update(Balance entity) {
		if (entity.getId() == null) {
			return store(entity);
		} else if (entity.getVersion().equals(find(entity.getId()).getVersion())) {
			return entity;
		}
		entity.incVersion();
		this.entities.put(entity.getId(), entity.clone());
		return entity;
	}
	
	@Override
	public List<Balance> getAll() {
		List<Balance> objects = new ArrayList<Balance>();
		for (Balance entity : entities.values()) {
			objects.add(entity.clone());
		}
		return objects;
	}
	
	public Balance findByRoommate(Integer roommateId) {
		for (Balance balance : entities.values()) {
			if (balance.getRoommate().getId().equals(roommateId)) {
				return balance.clone();
			}
		}
		return null;
	}
}
